Ext.BLANK_IMAGE_URL = '../ext-3.4/resources/images/default/s.gif';
Ext.Component.prototype.stateful = false;
Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
	expires : new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365))
})); // 设置过期时间，这里设置一年

Ext.onReady(function() {
	Ext.QuickTips.init();

	var vp = new Ext.Viewport({
		layout : 'border',
		items : new sys.JobPanel({
			region : 'center'
		})
	});
});

Ext.ns("sys");

sys.JobEditForm = Ext
		.extend(
				Ext.form.FormPanel,
				{
					constructor : function(cfg) {
						Ext.apply(this, cfg || {});
						this.jobId = new Ext.form.Hidden({
							fieldLabel : 'id',
							name : 'id'
						});
						this.previousFireTime = new Ext.form.Hidden({
							fieldLabel : 'previousFireTime',
							name : 'previousFireTime'
						});
						this.nextFireTime = new Ext.form.Hidden({
							fieldLabel : 'nextFireTime',
							name : 'nextFireTime'
						});
						this.isActive = new Ext.form.Hidden({
							fieldLabel : 'isActive',
							name : 'isActive',
							value : 0
						});
						this.jobName = new Ext.form.TextField({
							fieldLabel : '任务名称',
							name : 'jobName',
							allowBlank : false
						});
						this.beanName = new Ext.form.TextField({
							fieldLabel : '任务对象',
							name : 'beanName',
							allowBlank : false,
							helpText : '定时运行的 Spring Bean ID'
						});
						this.methodName = new Ext.form.TextField({
							fieldLabel : '任务方法',
							name : 'methodName',
							allowBlank : false,
							helpText : '定时运行的 Spring Bean 的无参方法名'
						});
						this.isConcurrent = new Ext.form.ComboBox({
							mode : 'local',
							fieldLabel : '是否并发',
							value : 0,
							hiddenField : 'key',
							valueField : 'key',
							displayField : 'value',
							emptyText : '请选择......',
							name : 'isConcurrent',
							hiddenName : 'isConcurrent',
							editable : false,
							triggerAction : 'all',
							allowBlank : false,
							store : new Ext.data.SimpleStore({
								data : [ [ 1, '是' ], [ 0, '否' ] ],
								fields : [ 'key', 'value' ]
							})
						});
						this.cronExpr = new Ext.form.TextField(
								{
									fieldLabel : '定时表达式',
									name : 'cronExpr',
									allowBlank : false,
									helpText : '使用cron表达式<br>*&nbsp;&nbsp;*&nbsp;&nbsp;*&nbsp;&nbsp;*&nbsp;&nbsp;*&nbsp;&nbsp;*<br>秒 分 时 日 月 周<br>第1列表示秒0-59 每秒钟用*或者*/1表示<br>第2列表示分0-59 <br>第3列表示时0-23<br>第4列表示日1-31<br>第5列表示月1-12<br>第6列表示星期0-6(0=星期天)'
								});
						this.startTime = new Ext.ux.form.DateTime({
							fieldLabel : '开始时间',
							name : 'startTime',
							dateFormat : 'Y-m-d',
							timeFormat : 'H:i:s',
							value : new Date()
						});

						this.endTime = new Ext.ux.form.DateTime({
							fieldLabel : '结束时间',
							name : 'endTime',
							dateFormat : 'Y-m-d',
							timeFormat : 'H:i:s'
						});
						this.description = new Ext.form.TextField({
							fieldLabel : '任务描述',
							name : 'description'
						});
						this.saveBtn = new Ext.Button({
							text : '新建',
							formBind : true,
							handler : function() {
								this.form.doAction('submit', {
									url : '../../job/saveJob.do',
									method : 'POST',
									scope : this,
									success : function(form, action) {
										this.reset();
										var jobGrid = this.jobPanel.jobGrid;
										jobGrid.getSelectionModel().clearSelections();
										jobGrid.refresh();
									},
									failure : function(form, action) {
										switch (action.failureType) {
										case Ext.form.Action.CLIENT_INVALID:
											Ext.Msg.alert("提示", "提交数据无效");
											break;
										case Ext.form.Action.CONNECT_FAILURE:
											Ext.Msg.alert("提示", "与服务器连接失败");
											break;
										case Ext.form.Action.SERVER_INVALID:
											Ext.Msg.alert("提示", action.result.msg);
										}
									}
								});
							},
							scope : this
						});
						this.reset = function() {
							this.form.reset();
							this.saveBtn.setText('新建');
						};

						this.edit = function(rec) {
							this.form.loadRecord(rec);
							this.saveBtn.setText('保存');
						};
						sys.JobEditForm.superclass.constructor.call(this, {
							id : '_job_eidt_form',
							baseCls : 'x-plain',
							labelAlign : 'right',
							labelWidth : 100,
							bodyStyle : "padding: 5px 5px 5px 5px;",
							monitorValid : true,
							defaults : {
								width : 650
							},
							items : [
									this.jobId,
									this.previousFireTime,
									this.nextFireTime,
									this.isActive,
									{
										layout : 'column',
										baseCls : 'x-plain',
										defaults : {
											columnWidth : 0.495
										},
										items : [
												{
													layout : 'form',
													baseCls : 'x-plain',
													defaults : {
														anchor : '98%'
													},
													items : [ this.jobName, this.beanName,
															this.startTime, this.isConcurrent ]
												},
												{
													layout : 'form',
													baseCls : 'x-plain',
													defaults : {
														anchor : '98%'
													},
													items : [ this.cronExpr, this.methodName,
															this.endTime, this.description ]
												} ]
									} ],
							buttons : [ this.saveBtn ]
						});
					}
				});

sys.JobGrid = Ext.extend(Ext.grid.GridPanel, {
	constructor : function(cfg) {
		Ext.apply(this, cfg || {});

		this.delBtn = new Ext.Button({
			text : '删除',
			iconCls : 'del',
			disabled : true,
			verify : function(sm) {
				return sm.getSelections().length > 0;
			},
			handler : function() {
				var ids = this.getSelectedIds();
				Ext.Msg.confirm('提示', '是否删除选中项,共[' + ids.length + ']条', function(msg) {
					if (msg == 'yes') {
						Ext.Ajax.request({
							url : '../../job/delJobs.do',
							method : 'POST',
							success : function(resp, opt) {
								this.refresh();
							},
							params : {
								ids : ids
							},
							scope : this
						});
					}
				}, this);
			},
			scope : this
		});

		this.activeBtn = new Ext.Button({
			text : '开始',
			iconCls : 'start',
			disabled : true,
			verify : function(sm) {
				var sels = sm.getSelections();
				if (sels.length == 0) {
					return false;
				}
				for ( var i = 0; i < sels.length; i++) {
					if (sels[i].data["isActive"] == true) {
						return false;
					}
				}
				return true;
			},
			handler : function() {
				var ids = this.getSelectedIds();
				Ext.Ajax.request({
					url : '../../job/activeJobs.do',
					method : 'POST',
					success : function(resp, opt) {
						var result = Ext.util.JSON.decode(resp.responseText);
						if (!result.success) {
							Ext.Msg.alert('错误', result.msg);
						}
						this.refresh();
					},
					params : {
						ids : ids
					},
					scope : this
				});
			},
			scope : this
		});

		this.disActiveBtn = new Ext.Button({
			text : '停止',
			iconCls : 'stop',
			disabled : true,
			verify : function(sm) {
				var sels = sm.getSelections();
				if (sels.length == 0) {
					return false;
				}
				for ( var i = 0; i < sels.length; i++) {
					if (sels[i].data["isActive"] == false) {
						return false;
					}
				}
				return true;
			},
			handler : function() {
				var ids = this.getSelectedIds();
				Ext.Ajax.request({
					url : '../../job/disActiveJobs.do',
					method : 'POST',
					success : function(resp, opt) {
						var result = Ext.util.JSON.decode(resp.responseText);
						if (!result.success) {
							Ext.Msg.alert('错误', result.msg);
						}
						this.refresh();
					},
					params : {
						ids : ids
					},
					scope : this
				});
			},
			scope : this
		});

		this.searcher = new Ext.form.TwinTriggerField({
			width : 150,
			trigger1Class : 'x-form-clear-trigger',
			trigger2Class : 'x-form-search-trigger',
			hideTrigger1 : true,
			emptyText : '输入关键字查询',
			grid : this,
			onTrigger1Click : function(e) {
				this.reset();
				this.onTrigger2Click(e);
			},
			onTrigger2Click : function(e) {
				var text = this.getValue().trim();
				if (text) {
					Ext.apply(this.grid.getStore().baseParams, {
						queryText : text
					});
					this.triggers[0].show();
				} else {
					this.reset();
					this.triggers[0].hide();
					Ext.destroyMembers(this.grid.getStore().baseParams, 'queryText');
				}
				this.grid.refresh();
			},
			listeners : {
				'specialkey' : {
					fn : function(fild, e) {
						if (e.getKey() == e.ENTER) {
							this.searcher.onTrigger2Click.call(this.searcher);
						}
					},
					scope : this
				}
			}
		});
		this.store = new Ext.data.JsonStore({
			url : '../../query/pageQuery.do',
			baseParams : {
				type : 'hql',
				text : 'from CommonJobDetail job where 1=1',
				'querySegments[0].condition' : 'queryText!=void',
				'querySegments[0].text' : "and job.jobName like '%${queryText}%'"
			},
			method : 'POST',
			totalProperty : 'count',
			root : 'data',
			fields : [ 'id', 'jobName', 'beanName', 'methodName', 'isActive',
					'isConcurrent', 'cronExpr', 'startTime', 'endTime',
					'previousFireTime', 'nextFireTime', 'description' ]
		});
		this.csm = new Ext.grid.CheckboxSelectionModel({
			listeners : {
				'selectionchange' : {
					fn : function(sm) {
						this.jobPanel.jobEditForm.reset();
						var rec = sm.getSelected();
						if (rec) {
							this.jobPanel.jobEditForm.edit(rec);
						}
						Ext.each(this.getTopToolbar().items.getRange(), function(item,
								index, all) {
							if (item.verify) {
								item.setDisabled(!item.verify(sm));
							}
						}, this);
					},
					scope : this
				}
			}
		});

		this.cm = new Ext.grid.ColumnModel({
			defaults : {
				sortable : true,
				width : 130
			},
			columns : [ new Ext.grid.RowNumberer(), this.csm, {
				id : 'jobName',
				header : '任务名称',
				dataIndex : 'jobName'
			}, {
				id : 'isActive',
				header : '是否活动',
				dataIndex : 'isActive',
				width : 80,
				renderer : function(val, meta) {
					if (val == true) {
						meta.attr = 'style="color:green"';
						return '是';
					} else if (val == false) {
						return '否';
					} else {
						return '';
					}
				}
			}, {
				id : 'cronExpr',
				header : '定时表达式',
				dataIndex : 'cronExpr'
			}, {
				id : 'previousFireTime',
				header : '上次执行时间',
				dataIndex : 'previousFireTime'
			}, {
				id : 'nextFireTime',
				header : '下次执行时间',
				dataIndex : 'nextFireTime'
			}, {
				id : 'beanName',
				header : '任务对象',
				dataIndex : 'beanName'
			}, {
				id : 'methodName',
				header : '任务方法',
				dataIndex : 'methodName'
			}, {
				id : 'isConcurrent',
				header : '是否并发',
				dataIndex : 'isConcurrent',
				width : 80,
				renderer : function(val, meta) {
					if (val == true) {
						return '是';
					} else if (val == false) {
						return '否';
					} else {
						return '';
					}
				}
			}, {
				id : 'startTime',
				header : '开始时间',
				dataIndex : 'startTime'
			}, {
				id : 'endTime',
				header : '结束时间',
				dataIndex : 'endTime'
			}, {
				id : 'description',
				header : '任务描述',
				dataIndex : 'description',
				width : 200
			} ]
		});
		this.refresh = function() {
			this.getSelectionModel().clearSelections();
			this.getBottomToolbar().doLoad(this.getBottomToolbar().cursor);
		};
		this.getSelected = function() {
			return this.getSelectionModel().getSelected();
		};
		this.getSelections = function() {
			return this.getSelectionModel().getSelections();
		};
		this.getSelectedIds = function() {
			var ids = [];
			var records = this.getSelectionModel().getSelections();
			if (!records)
				return ids;
			for ( var i = 0; i < records.length; i++) {
				ids.push(records[i].data.id);
			}
			return ids;
		};
		sys.JobGrid.superclass.constructor.call(this, {
			id : '_job_grid',
			store : this.store,
			loadMask : true,
			stripeRows : true,
			sm : this.csm,
			cm : this.cm,
			tbar : [ this.delBtn, '-', this.activeBtn, this.disActiveBtn, '-',
					this.searcher ],
			bbar : new Ext.PagingToolbar({
				store : this.store,
				displayInfo : true
			}),
			listeners : {
				'render' : {
					fn : function() {
						this.refresh();
					},
					scope : this
				}
			}
		});
	}
});

sys.JobPanel = Ext.extend(Ext.Panel, {
	constructor : function(cfg) {
		Ext.apply(this, cfg || {});
		this.jobEditForm = new sys.JobEditForm({
			id : '_job_edit_form',
			region : 'center',
			jobPanel : this
		});
		this.jobGrid = new sys.JobGrid({
			title : '定时任务列表',
			region : 'center',
			jobPanel : this
		});
		sys.JobPanel.superclass.constructor.call(this, {
			id : '_job_panel',
			layout : 'border',
			items : [ {
				region : 'north',
				title : '编辑查看',
				height : 180,
				split : true,
				collapsible : true,
				layout : 'border',
				items : this.jobEditForm
			}, this.jobGrid ]
		});
	}
})